import React, { FC, useState, useEffect, useRef, useMemo } from 'react'
import { Typography, Spin, Empty } from 'antd'
import { useTitle, useDebounceFn, useRequest } from 'ahooks'
import { useSearchParams } from 'react-router-dom'
import { LIST_PAGE_SIZE, LIST_SEARCH_PARAM_KEY } from '../../constant/index'
import { getQuestionListServices } from '../../services/question'
import QuestionCard from '../../components/QuestionCard'
import ListSearch from '../../components/ListSearch'
// import useLoadQuestionListData from '../../hooks/useLoadQuestionListData'
import styles from './common.module.scss'

const { Title } = Typography

const List: FC = () => {
    useTitle('滕轶男-个人问卷')
    const [started, setStarted] = useState(false) // 是否已经开始加载
    const [page, setPage] = useState(1) // URL不体现，只是List内部数据
    const [list, setList] = useState([]) // 累计全部列表数据
    const [total, setTotal] = useState(0)

    // url中没有page和pageSize，但是有keyword。搜索关键字变化时，也需要重新加载数据
    const [searchParams] = useSearchParams()
    const haveMoreData = total > list.length // 是否还有数据, true是还有数据
    const keyword = searchParams.get(LIST_SEARCH_PARAM_KEY) || ''

    // 当搜索内容发生变化时，页面的内容要重新加载。
    useEffect(() => {
        setStarted(false)
        setPage(1)
        setList([])
        setTotal(0)
    }, [keyword])

    const { run: load, loading } = useRequest(
        async () => {
            const data = await getQuestionListServices({
                page,
                pageSize: LIST_PAGE_SIZE,
                keyword,
            })
            return data
        },
        {
            manual: true,
            onSuccess(res) {
                const { list: l = [], total = 0 } = res
                setList(list.concat(l))
                setTotal(total)
                setPage(page + 1)
            },
        }
    )

    // 触发加载函数
    const containerRef = useRef<HTMLDivElement>(null)
    const { run: tryLoadMore } = useDebounceFn(
        () => {
            const elem = containerRef.current
            if (elem == null) return
            const domRect = elem.getBoundingClientRect()
            if (domRect == null) return

            const { bottom } = domRect
            if (bottom <= document.body.clientHeight) {
                load()
                setStarted(true)
            }
        },
        {
            // 模拟加载更多的接口返回数据的时间
            wait: 1000,
        }
    )
    // 当页面加载 或者 URL变化的时候触发
    useEffect(() => {
        tryLoadMore()
    }, [searchParams])

    // 当页面滚动时，尝试触发数据加载
    useEffect(() => {
        if (haveMoreData) {
            // 需要考虑防抖
            window.addEventListener('scroll', tryLoadMore)
        }
        return () => {
            // 销毁时解绑
            window.removeEventListener('scroll', tryLoadMore)
        }
    }, [searchParams, haveMoreData])

    const LoadMoreContentElem = useMemo(() => {
        // 未开始加载数据 || 数据加载中才展示loading
        if (!started || loading)
            return (
                <div style={{ textAlign: 'center' }}>
                    <Spin />
                </div>
            )
        if (total === 0) return <Empty description="暂无数据" />
        if (!haveMoreData) return <span>到头啦~~</span>
        return <span>上划加载下一页</span>
    }, [started, loading, haveMoreData])

    return (
        <>
            <div className={styles.header}>
                <div className={styles.left}>
                    <Title level={3}>问卷列表（我的问卷）</Title>
                </div>
                <div className={styles.right}>
                    <ListSearch />
                </div>
            </div>
            <div className={styles.content}>
                {list.length > 0 &&
                    list.map((qItem: any) => {
                        const { _id } = qItem
                        return <QuestionCard key={_id} {...qItem} />
                    })}
            </div>
            <div className={styles.footer}>
                <div ref={containerRef}>{LoadMoreContentElem}</div>
            </div>
        </>
    )
}

export default List
